<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2019/11/13
 * Time: 15:45
 */

namespace Rain\Admin\Services\Business\Common\Share;


trait SharedModel
{
    protected $field = ['*'];

    protected $pages = 10;

    protected $isPage = false;

    /**
     * 查询全部
     *
     * @param $query
     * @return mixed
     */
    protected function all($query){
        // 是否分页查询
        if($this -> isPage) {
            $list = $query -> paginate($this -> pages);
        } else {
            $list = $query -> get();
        }

        return $list;
    }

    /**
     * 查询单条
     *
     * @param $query
     * @return mixed
     */
    protected function find($query){
        return $query -> first();
    }

    /**
     * 查询列
     *
     * @param $query
     * @return mixed
     */
    protected function pluck($query){
        return $query -> pluck(implode('', $this -> field));
    }

    /**
     * 查询单个值
     *
     * @param $query
     * @return mixed
     */
    protected function value($query){
        return $query -> value(implode('', $this -> field));
    }

    /**
     * 添加
     *
     * @param $model
     * @param $data
     * @return mixed
     */
    protected function add($model, $data){
        return $model::create($data);
    }

    /**
     * 更新
     *
     * @param $query
     * @param $data
     * @return mixed
     */
    protected function update($query, $data){
        if(count($data) == count($data, 1)) {
            if(!$model = $query -> first()) return $model;

            $model -> update($data);

            return $model;
        } else {
            return $query -> update($data);
        }
    }

    /**
     * 删除
     *
     * @param $query
     * @return mixed
     */
    protected function del($query){
        if(!$model = $query -> first()) return $model;

        $model -> delete();

        return $model;
    }

    /**
     * 更新单个值
     *
     * @param $id
     * @param $data
     * @return mixed
     */
    public function updateIndividualValue($id, $data){
        return $this -> update($this -> getModelClass($id), $data);
    }
}
